﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.SharePoint;

namespace Shweet.SPSolution.ShweetReader
{
    public class Parser
    {
        public static string ConvertTagsToLinks(string suppiledString, string [] tags)
        {
            Contract.Requires(suppiledString != null);
            Contract.Requires(tags != null);
            Contract.ForAll(tags, t => t != null);

            suppiledString = LookAtEachTagAndConvertToAHTMLLink(suppiledString, tags);
            return suppiledString;
        }

        private static string LookAtEachTagAndConvertToAHTMLLink(string suppiledString, string[] tags)
        {
            foreach (var tag in tags)
            {
                //suppiledString = suppiledString.Replace(tag, string.Format("<a href='_self'>{0}</a>",tag));
                string regexString = "";
                if (!string.IsNullOrEmpty(tag))
                {
                    regexString = GenerateRegExForCaseInsensitiveReplace(tag, regexString);
                    string url = SPContext.Current.Web.Url;
                    url = string.Format("{0}?tag={1}",url, tag);
                    string encodedUrl = HttpUtility.HtmlEncode(url);
                    suppiledString = Regex.Replace(suppiledString, regexString, string.Format("<a href='{0}'>{1}</a>", encodedUrl, tag));                    
                }
            }
            return suppiledString;
        }

        private static string GenerateRegExForCaseInsensitiveReplace(string tag, string regexString)
        {
            foreach (char c in tag)
            {
                regexString += "[" + c.ToString().ToLower() + c.ToString().ToUpper() + "]";
            }
            return regexString;
        }
    }
}
